package com.miao.im.filter;

import com.miao.im.common.Message;
import com.miao.im.server.session.SessionContext;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/2 10:23
 * @Description:
 */
@Component
public class MessageFilterContext implements InitializingBean {

    private List<AbstractMessageFilter> filters;
    @Autowired
    private ApplicationContext applicationContext;

    public boolean execute(Message message, SessionContext sessionContext) {
        for (AbstractMessageFilter filter : this.filters) {
            if (!filter.doFilter(message, sessionContext)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, AbstractMessageFilter> beans = applicationContext.getBeansOfType(AbstractMessageFilter.class);
        this.filters = new ArrayList<>(beans.values());
        Collections.sort(this.filters);
    }
}
